import WebUploader from 'webuploader/dist/webuploader.js';

function techTrainingCtrl($rootScope, $scope, $http, ngDialog, paFetchService, ngDialogTechTraining) {
  'ngInject';

  let userInfo = JSON.parse(localStorage.getItem('userInfo'));

  // 角色 1代表指挥部，2代表监理单位 3代表施工单位
  $scope.$watch('techTraining.selectItem', function(newValue) {
    this.selectItem = newValue;
    if (this.selectItem) {
      this.loginType = this.selectItem.orgType ? this.selectItem.orgType : 1;
    }
    if (this.selectItem) {
      this.loginType = this.selectItem.orgType ? this.selectItem.orgType : 1;
      if (this.selectItem.orgType == 1) {
        this.isShowAddInfoZhb = true;
      } else if ((this.selectItem.orgType == 2 || this.selectItem.orgType == 3) && userInfo.role == 0) {
        this.loginType = 1;
        this.isShowAddInfoZhb = false;
      } else if (this.selectItem.orgType == 2) {
        this.isShowAddInfoZjb = true;
      } else if ((this.selectItem.orgType == 1 || this.selectItem.orgType == 3) && userInfo.role == 1) {
        this.loginType = 2;
        this.isShowAddInfoZjb = false;
      } else if (this.selectItem.orgType == 3) {
        this.isShowAddInfoXmb = true;
      } else if ((this.selectItem.orgType == 1 || this.selectItem.orgType == 2) && userInfo.role == 2) {
        this.loginType = 3;
        this.isShowAddInfoXmb = false;
      }
    }
  }.bind(this));

  this.educationList = {
    trainType: '1',
  };

  // 分页
  this.paginationData = {
    pageNum: 1,
    pageSize: 10,
    total: '',
  }

  // 获取组织部门
  paFetchService
    .getSectionList()
    .then((resp) => {
      $scope.orgs = resp.data.data;
    });

  // 页码变化时调用方法
  $scope.pageChange = () => {
    $http.post(`${SERVER_CONTEXT}/api/education/queryEducationList`,
      angular.extend(this.educationList, this.paginationData)
        )
      .then((resp) => {
        if(resp.statusText = 'OK'){
          this.technicalItemList = resp.data.data;
          this.paginationData.total = resp.data.total;
        }
    });
  };

  // 分页查询方法
  this.paginationQuery = () => {
    $http.post(`${SERVER_CONTEXT}/api/education/queryEducationList`,
      angular.extend(this.educationList, this.paginationData)
        )
      .then((resp) => {
        if(resp.statusText = 'OK'){
          this.technicalItemList = resp.data.data;
          this.paginationData.total = resp.data.total;
        }
    });
  };

  // 查询
  this.query = (param) => {
    if(param.endTime.$viewValue && param.startTime.$viewValue){
      if (param.startTime.$viewValue < param.endTime.$viewValue) {
        this.paginationQuery();
    } else {
        layer.alert('培训开始时间应小于结束时间');
      }
    } else {
      this.paginationQuery();
    }
  }

  // 重置
  this.reset = () => {
    this.educationList = {
      trainType: '1',
      organizationDepartmentId: $rootScope.activeBid.orgId,
    };
  }

  // 新增教育培训信息
  this.openTrainingPlan = function(ctrl){
    ngDialog.open({
      template: 'openTrainingPlan',
      className: 'ngdialog-theme-default pa-special-check-item-list-theme',
      controllerAs: 'vm',
      scope: $scope,
      controller: function trainClarifyCtrl($http, $scope, $timeout, paFetchService) {
        'ngInject';
        let _this = this;
        this.techTrainList = {
          trainType: '1',
          educationTrainWorker: [],
          educationTrainConTeam: [],
        };
        this.techTrainList.trainType = '1';

        this.showTeam = false;

        this.profilesToken = []; // 相关附件文件token

        //yuxt 人员下拉多选
        this.isShowSelect = false;

        // 根据施工队获得人员列表 added by sunqy
        this.showWorkers = (team) => {
          if (team.initFlag) {
            team.isShowWorker = !!!team.isShowWorker;
            return;
          }
          $http
            .get(`${SERVER_CONTEXT}/api/construction/select/${team.teamId}`)
            .then((resp) => {
              team.initFlag = true;
              team.workerInfoBeanList = resp.data;
              team.isShowWorker = !!!team.isShowWorker;
              team.workerInfoBeanList.forEach((worker) => {
                worker.constructionTeamName = team.teamName;
                worker.constructionTeamId = team.teamId;
              })
            })
        }

        this.checkAll = function(selectTeam,$event){
          if (!selectTeam.workerInfoBeanList) {
            $http
              .get(`${SERVER_CONTEXT}/api/construction/select/${selectTeam.teamId}`)
              .then((resp) => {
                selectTeam.initFlag = true;
                selectTeam.workerInfoBeanList = resp.data;
                selectTeam.isShowWorker = !!!selectTeam.isShowWorker;
                selectTeam.workerInfoBeanList.forEach((worker) => {
                  worker.constructionTeamName = selectTeam.teamName;
                  worker.constructionTeamId = selectTeam.teamId;
                  worker.checked = true;
                })
              })
          }
          var ele = $event.target;
          var flag = $(ele)[0].checked;
          if (flag) {
            selectTeam.isShowWorker = true;
          }
          $.each(this.teamWithOrgList,function(index,value){
            $.each(value.teamList,function(index1,team){
              if(team == selectTeam){
                $.each(team.workerInfoBeanList,function(index2,worker){
                  worker.checked = flag;
                });
              }
            });
          });
        };

        // 判断全选人
        this.isChange = (id) => {
          var bool = true;
          this.teamWithOrgList.forEach((org) => {
            org.teamList.forEach((team) => {
              if (id == team.teamId) {
                team.workerInfoBeanList.forEach((item) => {
                  if(!item.checked){
                      bool = false;
                  }
                })
                team.checked = bool;
              }
            })
          })
        }

        // 保存添加教育培训
        this.save = (param) => {

          // 修改表单是否提交过状态
          param.$submitted = true;

          // 表单校验
          if (param.$invalid) {
            return false;
          }

          let tempTeams = {};

          $.each(this.teamWithOrgList,function(index,value){
            $.each(value.teamList,function(index1,team){
              $.each(team.workerInfoBeanList,function(index2,worker){
                if (worker.checked) {
                  _this.techTrainList.educationTrainWorker.push({
                    workerId:worker.id,
                    constructionTeamId:worker.constructionTeamId,
                    workerName:worker.workerName
                  });

                  tempTeams[worker.constructionTeamId] = worker.constructionTeamName;

                }
              });
            });
          });

          for (var key in tempTeams) {
            _this.techTrainList.educationTrainConTeam.push({
              constructionTeamId: key,
              constructionTeamName: tempTeams[key],
            });
          }

          // 上传文件token
          this.files = [];
          this.profilesToken.forEach((item) => {
            this.files.push(item.id);
          });

          this.techTrainList.attachment = this.files.join(',');
          if (ctrl.loginType == 1) {
            $http
                .post(`${SERVER_CONTEXT}/api/education/insertEducationInfoByZhb`,
                  this.techTrainList)
                .then((resp) => {
                  if(resp.data.success){
                    layer.msg('添加教育信息成功');
                    $state.reload();
                    $scope.closeThisDialog();
                  }
                });
          }

          if (ctrl.loginType == 2) {
            $http
                .post(`${SERVER_CONTEXT}/api/education/insertEducationInfoByZjb`,
                  this.techTrainList)
                .then((resp) => {
                  if(resp.data.success){
                    layer.msg('添加教育信息成功');
                    $state.reload();
                    $scope.closeThisDialog();
                  }
                });
          }

          if (ctrl.loginType == 3) {
            $http
                .post(`${SERVER_CONTEXT}/api/education/insertEducationInfo`,
                  this.techTrainList)
                .then((resp) => {
                  if(resp.data.success){
                    layer.msg('添加教育信息成功');
                    $state.reload();
                    $scope.closeThisDialog();
                  }
                });
          }

        };

        // 初始化页面
        this.initPage = () => {
          // 获得施工队list
          paFetchService
            .getSpecialTeamWithOrgList()
            .then((resp) => {
              this.teamWithOrgList = resp.data;
            });
        }

        this.initPage();

      }
    });
  }

  // 查看教育培训信息
  this.queryDisclosure = function(id){
    ngDialogTechTraining
      .confirm(id);
  }

  // 编辑教育培训信息
  this.editDisclosure = function (param, ctrl) {
    ngDialog.open({
      template: 'alterInfoDisclosure',
      className: 'ngdialog-theme-default pa-special-check-item-list-theme',
      scope: $scope,
      controllerAs: 'vm',
      controller: function editTechCtrl($scope, $http, $timeout, paFetchService) {
       'ngInject';

        let _this = this;

        this.disclosureList = {};

        // 保存上传文件返回token
        this.profilesToken = [];

        this.getWorkersByTeamId = (team) => {

          if (team.initFlag) {
            team.isShowWorker = !!!team.isShowWorker;
            return;
          }
          $http
            .get(`${SERVER_CONTEXT}/api/education/queryEducationWorkerByCheck/${team.teamId}/${param.id}`)
            .then((resp) => {
              team.initFlag = true;
              team.workerInfoBeanList = resp.data;
              team.isShowWorker = !!!team.isShowWorker;
              team.workerInfoBeanList.forEach((worker) => {
                worker.checked = worker.checked ? true : false;
                worker.constructionTeamName = team.teamName;
                worker.constructionTeamId = team.teamId;
              });
              // 判断是否全选
              team.checked = true;
              team.workerInfoBeanList.forEach((worker) => {
                if (!worker.checked){
                  team.checked = false;
                }
              });

            });

        }

        // 根据施工队获得人员列表 added by sunqy
        this.showWorkers = (team) => {
          this.getWorkersByTeamId(team);
        }

        // 全选
        this.checkAll = function(selectTeam,$event){
          if (!selectTeam.workerInfoBeanList) {
            $http
              .get(`${SERVER_CONTEXT}/api/construction/select/${selectTeam.teamId}`)
              .then((resp) => {
                selectTeam.initFlag = true;
                selectTeam.workerInfoBeanList = resp.data;
                selectTeam.isShowWorker = !!!selectTeam.isShowWorker;
                selectTeam.workerInfoBeanList.forEach((worker) => {
                  worker.constructionTeamName = selectTeam.teamName;
                  worker.constructionTeamId = selectTeam.teamId;
                  worker.checked = true;
                })
              })
          }

          var ele = $event.target;
          var flag = $(ele)[0].checked;
          if (flag) {
            selectTeam.isShowWorker = true;
          }
          $.each(this.teamWithOrgList,function(index,value){
            $.each(value.teamList,function(inx,team){
              if(team == selectTeam){
                $.each(team.workerInfoBeanList,function(ix,worker){
                  worker.checked = flag;
                });
              }
            });
          });
        };

        // 判断全选人
        this.isChange = (id) => {
          var bool = true;
          this.teamWithOrgList.forEach((org) => {
            org.teamList.forEach((team) => {
              if (id == team.teamId) {
                team.workerInfoBeanList.forEach((item) => {
                  if(!item.checked){
                      bool = false;
                  }
                })
                team.checked = bool;
              }
            })
          })
        }

        // 获取教育详情
        this.getDetail = () => {
          $http.get(`${SERVER_CONTEXT}/api/education/queryEducationInfo/${param.id}`)
              .then((resp) => {
                this.disclosureList = resp.data;
                this.disclosureList.educationTrainWorker = [];

                if (!this.disclosureList.fileBeans) {
                  this.disclosureList.fileBeans = [];
                }

              });
        }

        // 编辑保存教育交底列表信息
        this.submit = (param) => {

          // 修改表单是否提交过状态
          param.$submitted = true;

          // 表单校验
          if (param.$invalid) {
            return false;
          }

          _this.disclosureList.educationTrainConTeam = [];
          _this.disclosureList.educationTrainWorker = [];
          let tempTeams = {};
           $.each(this.teamWithOrgList,function(index,value){
            $.each(value.teamList,function(inx,team){
              $.each(team.workerInfoBeanList,function(ix,worker){
                if (worker.checked) {
                  _this.disclosureList.educationTrainWorker.push({
                    workerId: worker.workerId ? worker.workerId : worker.id,
                    constructionTeamId: worker.constructionTeamId,
                    workerName: worker.workerName
                  });

                  tempTeams[worker.constructionTeamId] = worker.constructionTeamName;
                }
              });
            });
          });

          for (var key in tempTeams) {
            _this.disclosureList.educationTrainConTeam.push({
              constructionTeamId: key,
              constructionTeamName: tempTeams[key],
            });
          }

          let fileTokens = this.disclosureList.fileBeans;
          this.files = [];
          this.disclosureList.fileBeans.forEach((item) => {
            this.files.push(item.id);
          })
          this.disclosureList.attachment = this.files.join(',');

          if (ctrl.loginType == 1) {
            $http.post(`${SERVER_CONTEXT}/api/education/updateEducationInfoByZhb`,
              this.disclosureList
                ).
                then((resp) => {
                  if(resp.data.success){
                    layer.msg(resp.data.message);
                    $state.reload();
                    $scope.closeThisDialog();
                  }
                });
          }

          if (ctrl.loginType == 2) {
            $http.post(`${SERVER_CONTEXT}/api/education/updateEducationInfoByZjb`,
              this.disclosureList
                ).
                then((resp) => {
                  if(resp.data.success){
                    layer.msg(resp.data.message);
                    $state.reload();
                    $scope.closeThisDialog();
                  }
                });
          }

          if (ctrl.loginType == 3) {
            $http.post(`${SERVER_CONTEXT}/api/education/updateEducationInfo`,
              this.disclosureList
                ).
                then((resp) => {
                  if(resp.data.success){
                    layer.msg(resp.data.message);
                    $state.reload();
                    $scope.closeThisDialog();
                  }
                });
          }
        }

        // 初始化页面
        this.initPage = () => {
          // 获取列表信息
          this.getDetail();
          // 获得施工队list
          paFetchService
            .getSpecialTeamWithOrgList()
            .then((resp) => {
              this.teamWithOrgList = resp.data;
              this.teamWithOrgList.forEach((org) => {
                org.teamList.forEach((team) => {
                  param.educationTrainConTeam.forEach((item) => {
                    if (item.constructionTeamId == team.teamId) {
                      this.getWorkersByTeamId(team);
                    }
                  })
                })
              })
            });
        }

        this.initPage();

      }
    });
  };

  // 删除信息
  this.delete = (id) => {
    let _this = this;
    $scope.modalTitle = '删除教育培训';
    $scope.modalContent = '确认要删除该信息吗?';
    ngDialog.openConfirm({
      template: 'paConfirm',
      className: 'ngdialog-theme-default pa-confirm-theme',
      scope: $scope,
    }).
      then((value) => {
        if (this.loginType == 1) {
          $http.delete(`${SERVER_CONTEXT}/api/education/deleteEducationInfoByZhb/${id}`).
            then((resp) => {
              if(resp.data.success){
                layer.msg(resp.data.message);
                $state.reload();
              }
            });
        }
        if (this.loginType == 2) {
          $http.delete(`${SERVER_CONTEXT}/api/education/deleteEducationInfoByZjb/${id}`).
            then((resp) => {
              if(resp.data.success){
                layer.msg(resp.data.message);
                $state.reload();
              }
            });
        }
        if (this.loginType == 3) {
          $http.delete(`${SERVER_CONTEXT}/api/education/deleteEducationInfo/${id}`).
            then((resp) => {
              if(resp.data.success){
                layer.msg(resp.data.message);
                $state.reload();
              }
            });
        }

      }, (reason) => {});
  };

  // 升序、降序
  this.up = (param,index) => {
    this.educationList.columeName = param;
    this.educationList.order = index;
    this.paginationQuery();
  }

  // 初始化页面信息
  this.initPage = () => {
    // 获得施工队list
    paFetchService
      .getSpecialTeamWithOrgList()
      .then((resp) => {
        this.teamWithOrgList = resp.data;
      });
    // 获取教育交底列表信息
    // this.paginationQuery();

  }

  // 初始化页面
  this.initPage();

}

export default techTrainingCtrl;